﻿//=============================================================
// Copyright (C) 2011 深圳市中旭企业管理股份有限公司
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 用于生成数据结果的JSON数据格式
// URL parameter:
//        entity:当前实体对象名称(不一定是表名)
//        codition:过滤数据条件
//        pageindex:当前页
//        pagesize:页记录数
//        type:JSON的数据类型，有时候用于List.aspx使用，有时用于生成对应的JS Obecjt Entity!
//        order:排序
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉    
// 1.01   2011/11/21   江怀玉            增加获取数据权限功能
// 1.02   2011/11/23   江怀玉            增加获取自定义查询条件功能
// 1.05   2012/02/29   江怀玉            增加自定义部门查询条件功能
// 1.06   2012/04/11   江怀玉            增加缓存数据
// 1.07   2013/05/27   曾洋              多条件查询去掉 and
//=============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Common;
using ZX.BLL;
using ZX.DBModule;
using System.Text.RegularExpressions;
using System.Text;


using ZX.Web.UI.Controls;
using ZX.BLL.Extend;
using ZX.BPM.Library;
using ZX.EHR.Library;
namespace ZX.Web.UI.Controls
{
    public partial class JSONList : BasePage
    {
        int iPageIndex = 0;
        int iPageSize = 25;
        protected void Page_Load(object sender, EventArgs e)
        {
            switch (GetStringFromQueryString("action", ""))
            {
                case "":
                    if (this.GetStringFromQueryString("entity", "") == "t_File")
                    {
                        GetFiles(); 
                    }
                    else
                    {
                        _GetData();
                    }
                    break;
                case "GetUserRight":
                    BUser buser = new BUser();
                    IList<SysFunction> list = buser.GetFunctionByUserId((Guid)this.UserId);
                    Response.Write(ZX.Common.Globals.ListToJson<SysFunction>(list));
                    break;
                case "getdirs":
                    IList<t_Dir> _dirList = GetDirList();
                    Response.Write(ZX.Common.Globals.ListToJson<t_Dir>(_dirList));
                    break;
                case "getfiles":
                    GetFiles();
                    break;
                default :
                    _GetData();
                    break;
            }
        }

        private void _GetData()
        {
            if (this.UserId == null)
            {
                Response.Write("[]");
                return;
            }
            string strEntity = this.GetStringFromQueryString("entity", "");                  //对应的实体
            string strCondition = this.GetStringFromQueryString("condition", "");            //系统特定条件
            string strCustomCondition = this.GetStringFromQueryString("customCondition", "");//自定义条件
            iPageIndex = this.GetIntFromQueryString("pageindex", 0);                         //第N页？
            iPageSize = this.GetIntFromQueryString("pagesize", 25);                          //页记录数？
            string IsOnlyTotal = this.GetStringFromQueryString("onlyTotal", "false");        //是否只回传记录总数?
            string IsDesc = this.GetStringFromQueryString("desc", "false");                  //Yes or No
            string IsSetCache = this.GetStringFromQueryString("setcache", "false");          //是否设置缓存
            string IsRefreshCache = this.GetStringFromQueryString("IsRefreshCache", "false");//是否刷新缓存
            // strCondition = Server.UrlDecode(strCondition);
            // strCustomCondition = Server.UrlDecode(strCustomCondition);
            // 系统数据权限

            strCustomCondition = strCustomCondition
                                 .Replace("@UserID", this.UserId.ToString())
                                 .Replace("@UserName", this.UserName);
            strCondition = strCondition
                                 .Replace("@UserID", this.UserId.ToString())
                                 .Replace("@UserName", this.UserName);

            

            if (strEntity == "V_HF_TaskInstanceView" && strCondition != "")
            {
                strCustomCondition = strCondition;
                strCondition = "";
            }

            strCondition = strCondition == "" ? getRoleCondition() : strCondition + (getRoleCondition() == "" ? "" : " and " + getRoleCondition());
            strCondition = strCondition == "" ? strCustomCondition : strCondition + (strCustomCondition == "" ? "" : " and " + strCustomCondition);
            
            if (strCondition.EndsWith("and "))
            {
                strCondition = strCondition.Substring(0, strCondition.Length - 4);
            }
            else if (strCondition.EndsWith("or "))
            {
                strCondition = strCondition.Substring(0, strCondition.Length - 3);
            }

            string strType = this.GetStringFromQueryString("type", "");
            string strOrder = this.GetStringFromQueryString("order", "");
            strEntity = strEntity.Split(',')[0];

            IList<BaseEntity> list = null;
            System.Data.DataTable listResult = null;
            int totalrecord = 0;
            //记录数
            if (IsOnlyTotal == "true")
            {
                if (this.EntityName == "V_HF_TaskInstanceView")
                {
                    totalrecord = GetTaskInstanceCount(strCondition, strCustomCondition);
                    //  GetTaskInstanceView(strCondition, strCustomCondition, out totalrecord);
                    //return;
                }
                else
                {
                    totalrecord = GetTotal(strEntity, strCondition);
                }
                Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
                return;
            }

            if (this.EntityName == "V_HF_TaskInstanceView")
            {

                list = GetTaskInstanceView(strCondition, strCustomCondition);
            }
            else
            {
                if (IsSetCache == "true")
                {
                    if (IsRefreshCache == "false")
                    {
                        SetCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                    }
                    else
                    {
                        RefreshCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                    }
                    return;
                }
                //if(ZX.Common.
                if ((GetCondtionCache(strEntity) == strCondition) && !string.IsNullOrEmpty(GetDataCache(strEntity, iPageIndex)))
                {
                    HttpContext.Current.Response.Write(GetDataCache(strEntity, iPageIndex));
                    return;
                }
                list = GetData(strEntity, iPageIndex, iPageSize, strOrder, strCondition);
            }



            if (list == null && (listResult == null || listResult.Rows.Count == 0))
            {
                HttpContext.Current.Response.Write("{\"total\":" + totalrecord.ToString() + ",\"rows\":[]}");
                return;
            }
            //int totalrecord = bll.GetRowCount(strCondition);
            //string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"rows\":[";

            //strFormat = strFormat + str + "]}";
            //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
            if (strType == "1")
            {
                string str = string.Empty;
                if (listResult != null)
                {
                    str = ZX.Common.Globals.DataTableToJSON(listResult);
                }
                else
                {

                    str = list.ToJSON();
                }
                str = str.Replace("\\", "\\").Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("[@@]", "\\");

                HttpContext.Current.Response.Write("[" + str.Replace("null", "").Replace("[A]", "&") + "]");
            }
            else
            {
                string str = string.Empty;
                if (listResult != null)
                {
                    str = ZX.Common.Globals.DataTableToJSON(listResult);

                    string strFormat = "{\"total\":" + totalrecord + ",\"rows\":[";
                    str = str.Replace("\n", " ").Replace("\\", "\\").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("[@@]", "\\");
                    strFormat = strFormat + str + "]}";

                    HttpContext.Current.Response.Write(strFormat);
                }
                else
                {
                    HttpContext.Current.Response.Write(GetListJson(list, totalrecord));
                }


            }
            //iSunContext.Current.Context.Response.Write("["+str+"]");
        }


        private int GetTaskInstanceCount(string _strCondition, string _strCustomCondition)
        {
            string WorkflowID = "";
            string WorkflowInfo = "";
            //取WorkFlowId
            if (!string.IsNullOrEmpty(_strCondition))
            {

                string regexStrid = "WorkFlowId='(?<key>.*?)'";
                Regex rid = new Regex(regexStrid, RegexOptions.None);
                Match mc = rid.Match(_strCondition);
                WorkflowID = mc.Groups["key"].Value;
            }
            //取查询数把
            if (!string.IsNullOrEmpty(_strCustomCondition))
            {
                //WorkFlowNo
                _strCustomCondition = _strCustomCondition.Replace("(", "").Replace(")", "").Replace("%", "").Replace("   ", "");

                string[] vals = _strCustomCondition.Split(new string[] { " and ", " or " }, StringSplitOptions.None);

                string r = "(?<key>[A-z]*).*'(?<val>.*?)'";
                Regex reg = new Regex(r, RegexOptions.IgnoreCase);
                foreach (string v in vals)
                {
                    Match match = reg.Match(v);
                    string key = match.Groups["key"].Value;
                    if (key == "WorkFlowNo" || key == "FlowInstanceCaption")
                    {
                        WorkflowInfo = match.Groups["val"].Value;
                    }
                    //Console.WriteLine(key + ":" + value);
                }


            }
            BHF_TaskInstanceView tv = new BHF_TaskInstanceView();
            return tv.GetTaskInstanceCount(WorkflowID, 
                WorkflowInfo, User.LoginName,
                iPageIndex, iPageSize);
       
        }

        private IList<BaseEntity> GetTaskInstanceView(string _strCondition, string _strCustomCondition)
        {
            string WorkflowID = "";
            string WorkflowInfo = "";
            //取WorkFlowId
            if (!string.IsNullOrEmpty(_strCondition))
            {

                string regexStrid = "WorkFlowId='(?<key>.*?)'";
                Regex rid = new Regex(regexStrid, RegexOptions.None);
                Match mc = rid.Match(_strCondition);
                WorkflowID = mc.Groups["key"].Value;
            }
            //取查询数把
            if (!string.IsNullOrEmpty(_strCustomCondition))
            {
                //WorkFlowNo
                _strCustomCondition = _strCustomCondition.Replace("(", "").Replace(")", "").Replace("%", "").Replace("   ", "");

                string[] vals = _strCustomCondition.Split(new string[] { " and ", " or " }, StringSplitOptions.None);
    
                string r = "(?<key>[A-z]*).*'(?<val>.*?)'";
                Regex reg = new Regex(r, RegexOptions.IgnoreCase);
                foreach (string v in vals)
                {
                    Match match = reg.Match(v);
                    string key = match.Groups["key"].Value;
                    if (key == "WorkFlowNo" || key == "FlowInstanceCaption")
                    {
                        WorkflowInfo = match.Groups["val"].Value;
                    }
                    //Console.WriteLine(key + ":" + value);
                }
            }
            iPageIndex = iPageIndex - 1;
            BHF_TaskInstanceView tv = new BHF_TaskInstanceView();
            return tv.GetTaskInstanceList(WorkflowID, WorkflowInfo, User.LoginName, iPageIndex, iPageSize);
         }
        public string GetListJson(IList<BaseEntity> list, int totalrecord)
        {
            string strFormat = "{\"total\":" + (totalrecord==0?list.Count:totalrecord) + ",\"rows\":[";
            string str = list.ToJSON().Replace("\n", " ").Replace("\\","\\").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("[@@]", "\\");
            strFormat = strFormat + str + "]}";
            return strFormat;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="iPageIndex"></param>
        /// <param name="iPageSize"></param>
        /// <param name="strOrder"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public IList<BaseEntity> GetData(string strEntity, int iPageIndex, int iPageSize, string strOrder, string strCondition)
        {
            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            _bll.entity = entity;
            BaseBussnies bll = _bll;
            
            //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
            bll.Order = strOrder;
            bll.Desc = "Yes";
            
            if (bll.PageIndex == 0)
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            }
            else
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysSplitPage("1=1") : bll.GetEntitysSplitPage(strCondition);
            }
        }

        //public IList<BaseEntity> GetDoTasksData(string strEntity, int iPageIndex, int iPageSize, string strOrder, string strCondition)
        //{
        //    BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
        //    _bll.entity = entity;
        //    BaseBussnies bll = _bll;

        //    //BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
        //    bll.PageIndex = iPageIndex;
        //    bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
        //    bll.Order = strOrder;
        //    bll.Desc = "Yes";

        //    if (bll.PageIndex == 0)
        //    {
        //        return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
        //    }
        //    else
        //    {
        //        return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysSplitPage("1=1") : bll.GetEntitysSplitPage(strCondition);
        //    }
        //}

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public int GetTotal(string strEntity, string strCondition)
        {
            BaseEntity entity = ZX.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            return bll.GetRowCount(strCondition);
        }
        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            IList<ZX.EHR.Library.SysRoleFunction> list = (new ZX.BLL.BUser()).GetRoleFunction(this.UserId,this.FunctionID);
            StringBuilder strCondition = new StringBuilder("");
            
            if (list == null)
            {
                return "";
            }
            foreach (var entity in list)
            {
                switch (entity.OperateRangeType.Trim())
                {
                    ///只能查看本人数据
                    case "0":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        else if (this.EntityName == "V_HF_ClaimedWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            break;
                        }
                        else if (this.EntityName == "V_HF_CompleteWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            break;
                        }
                        else if (this.EntityName == "V_HF_MyAllWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            break;
                        }
                        else if (this.EntityName == "V_HF_AbnormalTask")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", CSVHelper.FmSQL(User.LoginName)));
                            break;
                        }
                        else if (this.EntityName == "HF_WorkFlowInstanceView")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if(this.EntityName=="V_HF_WorkFlowDraftList") {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if (this.EntityName == "HF_WorkFlowApplicationView")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if (this.EntityName == "HF_WorkFlowApproveView")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if (this.EntityName == "HF_ErrorLogsView")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if (this.EntityName == "HF_WorkTaskInstanceCloseView")
                        {
                            strCondition.Append(string.Format(" UserId='{0}'", User.LoginName));
                            break;
                        }
                        else if (this.EntityName == "V_CrmValueRpt")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}' ", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmDeliverHr")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmDeliverMajorProInfo")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmDeliverTrain")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmActivityCall")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmManager")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmCustomerInfoOrders")
                        {
                            strCondition.Append(string.Format("CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmDeliverMajor")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else if (this.EntityName == "V_CrmPay")
                        {
                            strCondition.Append(string.Format(" CustomeerMgr='{0}' or  AddUser='{0}'", this.UserId));
                            break;
                        }
                        else
                        {
                            //if (strCondition.ToString() != "")
                            //{
                            //    strCondition.Append(" OR ");
                            //}
                            strCondition.Append(string.Format(" AddUser='{0}'", this.UserId));
                            break;
                        }
                        strCondition.Append("1=0");
                        break;
                    ///可以看本部门的
                    case "1":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR");
                        }
                        if (this.EntityName == "V_CrmCustomerShow"||this.EntityName == "V_CrmCustomerList" )
                        {
                            //strCondition.Append(string.Format(" AreaId in  (select  VALUE  from  fn_Split((select DEPTIDS  from dbo.V_UserEmp  where userid='{0}'),',')) and IsPrevate=0 and IsValue=1", this.UserId));    
                            //strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and IsPrevate='0' and IsValue='1'", this.UserId));
                            strCondition.Append(string.Format(" (AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and IsValue='1')", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmCustomerInfo")
                        {
                            string strTreeId = this.GetStringFromQueryString("condition", "");
                            if (strTreeId == "")
                            {
                                strCondition.Append(string.Format(" CustomUser='{0}' and IsValue='1'", this.UserId));
                            }
                            /*else
                            {
                                strCondition.Append(string.Format(" {0}", strTreeId));
                            }*/
                        }
                        else if (this.EntityName == "V_CrmCustomerOld")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and CustomerState=0", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmCustomerOldRubbish")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and CustomerState=2", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmCustomerOldStop")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and CustomerState=3", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmCustomerCooperation")
                        {
                            strCondition.Append(string.Format(" AreaId in  (select DeptID from V_CrmUserArea where UserID='" + UserId + "') and IsValue='1'", this.UserId));
                        }
                        //else if (this.EntityName == "HF_WorkFlowInstanceView")
                        //{
                        //    strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        //}
                        else if (this.EntityName == "V_HF_MyAllWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmValueRpt")
                        {
                            //价值业绩 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmDeliverHr")
                        {
                            //英才 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmDeliverMajorProInfo")
                        {
                            //项目 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmDeliverTrain")
                        {
                            //内训 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmActivityCall")
                        {
                            //行销记录 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmCustomerInfoOrders")
                        {
                            //订单 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmManager")
                        {
                            //联系人管理 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmDeliverMajor")
                        {
                            //大课管理 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_CrmPay")
                        {
                            //缴款单管理 客户经理
                            strCondition.Append(string.Format(" CustomeerMgr in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "V_HF_CompleteWorkTask")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "HF_WorkFlowApplicationView")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "HF_WorkFlowApproveView")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "HF_ErrorLogsView")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else if (this.EntityName == "HF_WorkTaskInstanceCloseView")
                        {
                            strCondition.Append(string.Format(" UserId in (select UserID from dbo.fn_GetLoginNameDeptUsers('{0}'))", this.UserId));
                        }
                        else
                        {
                            strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetUserDeptUsers('{0}'))", this.UserId));
                        }
                        break;
                    // 
                    // 全部数据
                    case "2":
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        //if (strCondition.ToString() == "")
                        //{
                        strCondition.Append("1=1");
                        // }
                        break;
                    //自定义部门条件
                    case "3":
                        // 如果自定义条件
                        if (strCondition.ToString() != "")
                        {
                            strCondition.Append(" OR ");
                        }
                        strCondition.Append(string.Format(" AddUser in (select UserID from dbo.fn_GetDeptsUsers('{0}'))", entity.Depts));
                        break;
                    // 自定义条件数据
                    case "4":
                        if (entity.Condition != string.Empty)
                        {
                            if (strCondition.ToString() != "")
                            {
                                strCondition.Append(" OR ");
                            }
                            strCondition.Append(" " + entity.Condition + " ");
                        }
                        
                        break;
                    default:
                        break;
                }
            }

            //只用客户用户时使用
            if (this.User.IsOutsite == true)
            {
                if (this.EntityName == "TrActivity")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }

                    strCondition.Append(string.Format("(TrCustomerID='{0}')", User.CustomerID));

                }
                if (this.EntityName == "V_TrActivityCourse")
                {
                    if (strCondition.ToString() != "")
                    {
                        strCondition.Append(" OR ");
                    }
                    strCondition.Append(string.Format("(TrCustomerID = '{0}')", User.CustomerID));
               }
            }
            return string.IsNullOrEmpty(strCondition.ToString())?"": "("+ strCondition.ToString()+")";
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="condition">页</param>
        public void SetCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            ZX.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition,60*20);
            int page = total / pagesize+1;
            page = page > 20 ? 20 : page;
            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                ZX.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="pageindex">页</param>
        /// <returns></returns>
        public string GetDataCache(string entity, int pageindex)
        {
            return ZX.Common.WebCache.Get(entity + "_" + this.UserName + "_" + pageindex) as string;
        }

        public string GetCondtionCache(string entity)
        {
            return ZX.Common.WebCache.Get(entity + "_" + this.UserName + "_Condition") as string;
        }

        public void RefreshCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            int page = total / pagesize + 1;
            page = page > 20 ? 20 : page;
            #region 去掉缓存
            ZX.Common.WebCache.Remove(entity + "_" + this.UserName + "_Condition");
            for(int i=1;i<page+1 ;i++)
            {
                ZX.Common.WebCache.Remove(entity + "_" + this.UserName + "_" + i);
            }
            #endregion
            ZX.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition, 60 * 20);

            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                ZX.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }

        #region FileManager
        public IList<t_Dir> GetDirList()
        {
           IList<t_Dir> list = new List<t_Dir>();
           System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Server.MapPath("\\"));
           list.Add(new t_Dir { Dir = "Root", DirPath =(dir.FullName.ToLower().EndsWith("\\")?dir.FullName.ToLower().Remove(dir.FullName.ToLower().Length-1,1):dir.FullName.ToLower()), ParentPath = "", CreateDate = dir.LastWriteTime });
           GetDirList(list, dir);
           foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
           {
               if("bin,app_code,app_data,app_themes,aspnet_client,clientbin,dll".Contains(_dir.Name.ToLower()))
               {
                   continue;
               }
               if (list.Where(p => p.DirPath == _dir.FullName.ToLower()).Count() == 0)
               {
                   list.Add(new t_Dir { Dir = _dir.Name, DirPath = _dir.FullName.ToLower(), ParentPath = _dir.Parent.FullName.ToLower(), CreateDate = dir.LastWriteTime });
               }
               GetDirList(list, _dir);
           }
           return list.Distinct().OrderBy(p=>p.DirPath).ToList();
        }

        public void GetDirList(IList<t_Dir> list, System.IO.DirectoryInfo dir)
        {
            //string root = Server.MapPath("\\").ToLower();
            foreach (System.IO.DirectoryInfo _dir in dir.GetDirectories())
            {
                if (list.Where(p => p.DirPath == _dir.FullName.ToLower()).Count() == 0)
                {
                    list.Add(new t_Dir { Dir = _dir.Name, DirPath = _dir.FullName.ToLower(), ParentPath = _dir.Parent.FullName.ToLower(), CreateDate = dir.LastWriteTime });
                }
                GetDirList(list, _dir);
            }
        }

        public IList<t_File> GetFiles(string path)
        {
            IList<t_File> list = new List<t_File>();
            System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(path);
            foreach(System.IO.FileInfo file in dir.GetFiles())
            {
                list.Add(new t_File { fileName=file.Name,filePath=file.FullName,size=file.Length/1024+"K",fileExt=file.Extension});
            }
            return list.Distinct().ToList();
        }

        public void GetFiles()
        {
            string path = GetStringFromQueryString("path", "");
            IList<t_File> _fileList = GetFiles(path);
            Response.Write("{rows:"+ZX.Common.Globals.ListToJson<t_File>(_fileList)+"}");
        }
        #endregion 
    }



    public class t_File
    {
        public string fileName
        {
            get;
            set;
        }

        public string fileExt
        {
            get;
            set;
        }

        public string size
        {
            get;
            set;
        }

        public string filePath
        {
            get;
            set;
        }
    }


    public class t_Dir
    {
           public string Dir
           {
               get;set;
           }

           public string DirPath{
               get;set;
           }

           public string ParentPath
           {
               get;
               set;
           }

           public DateTime CreateDate
           {
               get;
               set;
           }
    }
}
